<html>
<head>
	<title>Native Client</title>
	<meta name="author" content="kajweb@163.com">
</head>
<body>
<p><input type="text" id="wsIP"/><button onclick="connectSocket();">连接</button><button onclick="closeSocket();">关闭</button><button onclick="localhost();">本地</button></p>
<p><input type="text" id="text"/><button onclick="send();">发送</button></p>

<script>
//发送消息
var MySocket;
let defaultWs = "ws://121.40.165.18:8088"; //by http://www.blue-zero.com/WebSocket/
let defaultText = "测试文本";
let defaultLocalhost = "127.0.0.1";
let defaultLocalPort = "8999";

//设置默认地址和默认文本，方便调试
if(defaultWs!="")
	document.getElementById("wsIP").value = defaultWs;
if(defaultText!="")
	document.getElementById("text").value = defaultText;
	
function localhost(){
	document.getElementById("wsIP").value = "ws://" + defaultLocalhost + ":" + defaultLocalPort;
}

function send(){
	print('用户点击发送按钮请求发送WebSocket消息');
	if(!MySocket){
		print("WebSocket未初始化，请先连接");
		return false;
	}
	if(myState = MySocket.readyState == WebSocket.OPEN || MySocket.readyState == 1){
		let userInput = document.getElementById("text").value;
		MySocket.send(userInput);
		print("成功发送请求");
	}else{
		switch(myState){
		case 0:
		case WebSocket.CONNECTING:
			myState = "WebSocket正在连接。";
			break;
		case 2:
		case WebSocket.CLOSING:
			myState = "WebSocket正在连接。";
			break;
		case 3:
		case WebSocket.CLOSED:
			myState = "WebSocket连接已经关闭，或者打开连接失败。";
			break;
		default:
			myState = "其他错误，可能是WebSocket连接已经关闭，或者打开连接失败。";
		}
		print("发送请求失败: " + myState);
	}
}

//判断浏览器是否支持socket
function isSupportWebSocket(){
	if(window.WebSocket){
		print('当前浏览器支持：WebSocket');
		return window.WebSocket;
	}else{
		print('当前浏览器不支持：WebSocket');
		return false;
	}
}

function connectSocket(){
	//建立监听
	if(isSupportWebSocket){
		let wsIP = document.getElementById("wsIP").value;
		try{
			var Socket = new WebSocket(wsIP);
			print('新建WebSocket实例');
			MySocket = Socket;
		}catch(e){
			print('连接socket失败');
			return false;
		}
		
		
		MySocket.onopen = function(){
			print('启动socket服务');
		}

		MySocket.onmessage = function(e){
			print('接收到');
			print(e);
		}

		MySocket.onerror = function(){
			print('发送错误');
		}

		MySocket.onclose = function(){
			print('关闭socket服务');
		}
	}
}

function closeSocket(){
	print('用户点击按钮请求关闭WebSocket');
	if(!MySocket){
		print("WebSocket未初始化，请先连接");
		return false;
	}
	MySocket.close();
}

function print(p_w){
	console.log(p_w)
	return;
	document.write(p_w+"<br>");
}
/*
Note:
MySocket.readyState属性返回实例对象的当前状态，共有四种。
	CONNECTING：值为0，表示正在连接。
	OPEN：值为1，表示连接成功，可以通信了。
	CLOSING：值为2，表示连接正在关闭。
	CLOSED：值为3，表示连接已经关闭，或者打开连接失败。
*/
</script>
</body>
</html>